package cn.virens.web.components.spring.permission;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.virens.database.common.BaseEnum;

/**
 * 基础权限类型
 * 
 * @author virens
 */
public enum Permission implements BaseEnum<String> {

	/** 查看 */
	VIEW("view", "查看"),
	/** 管理 */
	MANAGE("manage", "管理");

	private String key;
	private String desc;

	private Permission(String key, String desc) {
		this.desc = desc;
		this.key = key;
	}

	@Override
	public String getKey() {
		return key;
	}

	@Override
	public String getDesc() {
		return desc;
	}

	@Override
	public boolean eq(String key) {
		return StrUtil.equals(key, this.key);
	}

	/**
	 * 判断 - 是否包含当前权限
	 * 
	 * @param  identity 权限
	 * @return          has
	 */
	public boolean has(String identity) {
		return StrUtil.isNotEmpty(identity) && identity.indexOf(this.key) > -1;
	}

	/**
	 * 检查 指定 权限是否存在于 权限数组中
	 * 
	 * @param  permission  查找权限
	 * @param  permissions 被查权限数组
	 * @return             has
	 */
	public static boolean has(Permission permission, Permission... permissions) {
		return permission != null && ArrayUtil.contains(permissions, permission);
	}

	/**
	 * 追加权限类型
	 * 
	 * @param  identity 权限类型
	 * @return          权限字符串
	 */
	public String parts(String identity) {
		return identity + ":" + this.key;
	}

	public static Permission parse(String key) {
		for (Permission temp : values()) {
			if (temp.eq(key)) { return temp; }
		}

		return null;
	}

	public static Permission[] array(String roles) {
		if (roles == null || roles.isEmpty()) { return null; }

		// 分割角色字符串
		String[] permissions = StrUtil.split(roles, ",");

		// 字符串数组转换为枚举数组
		Permission[] temp = new Permission[permissions.length];
		for (int i = 0; i < temp.length; i++) {
			temp[i] = Permission.parse(permissions[i]);
		}

		return repeated(temp);
	}

	public static String array(Permission... permissions) {
		if (ArrayUtil.isEmpty(permissions)) { return null; }

		// 将枚举数组转为字符串
		StringBuilder builder = new StringBuilder();
		for (Permission temp : repeated(permissions)) {
			builder.append(",").append(temp.key);
		}

		// 移除开头的逗号后返回字符串
		if (StrUtil.isNotEmpty(builder)) {
			return builder.deleteCharAt(0).toString();
		} else {
			return null;
		}
	}

	/**
	 * 对权限数组进行排重
	 * 
	 * @param  permissions 权限数组
	 * @return             权限数组
	 */
	public static Permission[] repeated(Permission... permissions) {
		Permission[] temp = new Permission[permissions.length];

		int index = 0;

		// 过滤重复权限
		for (Permission permission : permissions) {
			if (!has(permission, permissions)) {
				temp[index++] = permission;
			}
		}

		// 过滤空权限
		Permission[] answer = new Permission[index];
		for (int i = 0; i < answer.length; i++) {
			answer[i] = temp[i];
		}

		return answer;
	}

	@Override
	public String toString() {
		return this.key;
	}
}
